<template>
  <div>
    <!-- 如无需展开查询，请移除:advanced.sync="advanced"并添加:no-advanced="true" -->
    <e-pro-table title="资源管理" :advanced.sync="advanced" :no-advanced="true">
      <template slot="query">
        <a-col :xxl="6" :xl="8" :lg="12" :sm="24">
          <a-form-model-item label="名称">
            <a-input v-model="queryParam.name"/>
          </a-form-model-item>
        </a-col>
        <a-col :xxl="6" :xl="8" :lg="12" :sm="24">
          <a-form-model-item label="类型">
            <e-dict-select v-model="queryParam.type" type="cmsMediaType" @change="$refs.eTable.refresh(true)"/>
          </a-form-model-item>
        </a-col>
        <template v-if="advanced">
          <!-- 点击展开显示的查询条件 -->
        </template>
      </template>

      <template slot="button">
        <a-button type="primary" icon="plus" @click="()=>{this.uploadModalVisible = true}">
          新增
        </a-button>

        <e-btn-remove-batch
          permissions="cms:media:remove"
          :loading.sync="removeBathLoading"
          :ids="selectedRowKeys"
          :click-callback="remove"/>
      </template>

      <template slot="table">
        <s-table
          ref="eTable"
          :columns="columns"
          :data="loadData"
          :alert="true"
          :rowSelection="rowSelection"
          showPagination="auto"
        >
          <template #preview="text, record">
            <div v-if="record.type === 'image'">
              <div class="image-preview">
                <img :src="VUE_APP_API_BASE_URL + record.filePath">
              </div>
            </div>
            <div v-if="record.type !== 'image'">
              -
            </div>
          </template>
          <template #type="text">
            <e-dict-tag type="cmsMediaType" :code="text"/>
          </template>
          <template #action="text, record">
            <e-btn-remove permissions="cms:media:remove" :id="record.id" :divider="false" :click-callback="remove"/>
            <a-divider type="vertical"/>
            <a-tooltip placement="top">
              <template #title>
                <span>下载</span>
              </template>
              <a-button size="small" icon="download" @click="downloadSysFileById(record.id)"/>
            </a-tooltip>
            <a-divider type="vertical"/>
            <a-tooltip placement="top">
              <template #title>
                <span>查看</span>
              </template>
              <a-button size="small" icon="search" @click="openFile(record)"/>
            </a-tooltip>
          </template>
        </s-table>
      </template>
    </e-pro-table>

    <a-modal
      title="上传资源"
      :visible="uploadModalVisible"
      @cancel="() => {this.uploadModalVisible = false}"
    >
      <a-alert message="支持上传图片、音乐、视频、文档和压缩文件" type="info" show-icon/>
      <br/>

      <a-upload
        name="file"
        accept=".doc,.docx,.xlsx,.xls,.ppt,.pptx,.pdf,.txt,.zip,.7z,.rar,image/*,video/*,audio/*"
        :multiple="true"
        :action="`${VUE_APP_API_BASE_URL}/auth/file/upload`"
        :headers="headers"
        :file-list="files"
        :before-upload="beforeUpload"
        :remove="handleRemove"
        @change="handleChange"
      >
        <a-button>
          <a-icon type="upload"/>
          选择文件
        </a-button>
      </a-upload>

      <template slot="footer">
        <a-button @click="handleClose">
          关闭
        </a-button>
      </template>
    </a-modal>

    <cms-chose-site @change="changeSite"/>
  </div>
</template>

<script>
import { select, remove, save } from '@/api/cms/media'
import { downloadSysFileById, formatDate } from '@/utils/util'
import { STable, Ellipsis } from '@/components'
import EProTable from '@/components/Easy/data-display/ProTable'
import EBtnAdd from '@/components/Easy/general/BtnAdd'
import EBtnEdit from '@/components/Easy/general/BtnEdit'
import EBtnRemove from '@/components/Easy/general/BtnRemove'
import EBtnRemoveBatch from '@/components/Easy/general/BtnRemoveBatch'
import CmsChoseSite from '@/views/cms/ChoseSite'
import EUpload from '@/components/Easy/data-entry/Upload'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import EDictSelect from '@/components/Easy/data-entry/DictSelect'
import EDictTag from '@/components/Easy/data-display/DictTag'

const columns = [
  {
    title: '缩略图',
    dataIndex: 'preview',
    width: 160,
    scopedSlots: { customRender: 'preview' }
  },
  {
    title: '名称',
    dataIndex: 'name',
    width: 320,
    sorter: true
  },
  {
    title: '类型',
    dataIndex: 'type',
    width: 100,
    sorter: true,
    scopedSlots: { customRender: 'type' }
  },
  {
    title: '更新人',
    dataIndex: 'editUser',
    width: 100,
    sorter: true
  },
  {
    title: '更新时间',
    dataIndex: 'editDate',
    width: 170,
    sorter: true,
    customRender: (text) => formatDate(text)
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: 140,
    fixed: 'right',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'CmsMediaList',
  components: {
    EDictTag,
    EDictSelect,
    EUpload,
    CmsChoseSite,
    STable,
    Ellipsis,
    EProTable,
    EBtnAdd,
    EBtnEdit,
    EBtnRemove,
    EBtnRemoveBatch
  },
  data () {
    this.columns = columns
    return {

      // 查询参数
      advanced: false,
      queryParam: {},
      selectedRowKeys: [],
      selectedRows: [],
      removeBathLoading: false,

      // 上传
      uploadModalVisible: false,
      VUE_APP_API_BASE_URL: process.env.VUE_APP_API_BASE_URL,
      headers: {
        'Access-Token': storage.get(ACCESS_TOKEN)
      },
      maxFileSize: 512,
      files: []
    }
  },
  activated () {
    this.$refs.eTable.refresh(true)
  },
  computed: {
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    downloadSysFileById (pId) {
      downloadSysFileById(pId)
    },
    changeSite () {
      this.$refs.eTable.refresh(true)
    },
    // 加载数据方法 必须为 Promise 对象
    loadData (parameter) {
      const requestParameters = Object.assign({}, parameter, this.queryParam)
      return select(requestParameters)
        .then(res => {
          return res.data
        })
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    remove (id) {
      remove(id).then(res => {
        this.$refs.eTable.refresh(true)
        this.removeBathLoading = false
      }).catch(({ response }) => {
        this.removeBathLoading = false
      })
    },
    openFile (record) {
      window.open(this.VUE_APP_API_BASE_URL + record.filePath)
    },
    handleClose () {
      this.uploadModalVisible = false
      this.$refs.eTable.refresh(true)
    },
    handleRemove (file) {
      const index = this.files.indexOf(file)
      const newFileList = this.files.slice()
      newFileList.splice(index, 1)
      this.files = newFileList
    },
    beforeUpload (file) {
      if (file.size / 1024 / 1024 > this.maxFileSize) {
        this.$message.error(`文件大小超出限制，不能超过${this.maxFileSize}MB`)
        return false
      }
      return true
    },
    handleChange (info) {
      if (info.file.status) {
        if (info.file.status === 'done') {
          this.saveMedia(info.file.response.data)
        } else if (info.file.status === 'error') {
          this.$message.error(`${info.file.name || ''} 上传失败`)
        }
        this.files = info.fileList.filter(item => item.status !== 'done')
      }
    },
    saveMedia ({ name, path }) {
      save({ file: { displayName: name, path } }).then(res => {
        this.$message.success(`${res.data.name} 上传成功`)
      })
    }
  }
}
</script>
<style lang="less" scoped>
.image-preview {
  height: 44px;
  margin: -6px 0;
  position: relative;

  img {
    max-width: 100%;
    max-height: 100%;
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
  }

}
</style>
